#!/usr/bin/env python
# encoding: utf-8
import pandas as pd
from feature_set.loan.un.utils.loan_un_order_features import get_order_format
from feature_set.loan.un.utils.loan_un_installment_features import get_bill_data
from feature_set.base_feature import BaseFeature, RequstData
from feature_set.loan.un.loan_un_base_v3.loan_un_order_v3 import LoanUnOrderV3
from feature_set.loan.un.loan_un_base_v3.loan_un_payoff_v3 import LoanUnPayoffV3
from feature_set.loan.un.loan_un_base_v3.loan_un_ovdpayoff_v3 import LoanUnOvdPayoffV3
from feature_set.loan.un.loan_un_base_v3.loan_un_prepayoff_v3 import LoanUnPrePayoffV3


class LoanUnBaseV3(BaseFeature):
    def __init__(self):
        super().__init__()
        self.function_map = {
            'loan_order_features_v3': self.loan_order_features_v3,
            'loan_payoff_features_v3': self.loan_payoff_features_v3,
            'loan_pre_payoff_features_v3': self.loan_pre_payoff_features_v3,
            'loan_ovd_payoff_features_v3': self.loan_ovd_payoff_features_v3,
        }
        self.country_id = None

    def load_conf(self):
        """
        load config file
        Returns:

        """
        pass

    def load_request(self, request_data: RequstData):
        """
        get request data and format feature input data
        Args:
            request_data: input detail data

        Returns:
            format order and installment data
        """
        register_time = request_data.data_sources['user_info_1']['userInfo']['userRecord']['registerTime']

        current_loan_amount = -999
        current_product_code = ''
        if 'productInfo' in request_data.data_sources['user_info_1']:
            prod_info = request_data.data_sources['user_info_1']['productInfo']
            if type(prod_info) == dict:
                if 'productCode' in request_data.data_sources['user_info_1']['productInfo'] :
                    current_product_code = request_data.data_sources['user_info_1']['productInfo']['productCode']
                if 'amount' in request_data.data_sources['user_info_1']['productInfo']:
                    current_loan_amount = request_data.data_sources['user_info_1']['productInfo']['amount']
                    if current_loan_amount is None:
                        current_loan_amount = -999

        current_acq_channel = request_data.acq_channel
        current_apply_time = request_data.apply_time
        current_order_id = request_data.order_id
        current_info = {'current_apply_time': current_apply_time,
                        'current_acq_channel': request_data.acq_channel,
                        'current_order_id': request_data.order_id,
                        'current_loan_amount': current_loan_amount,
                        'current_product_code': current_product_code,
                        'register_time': register_time}
        # order data
        user_history_order = request_data.data_sources['order_data_a']
        if not user_history_order or user_history_order == []:
            user_history_order = pd.DataFrame(columns=['app_order_id',
                                                       'user_id',
                                                       'acq_channel',
                                                       'device_type',
                                                       'product_name',
                                                       'product_code',
                                                       'product_set_code',
                                                       'loan_amount',
                                                       'down_payment',
                                                       'user_name',
                                                       'id_card_number',
                                                       'phone_number',
                                                       'apply_time',
                                                       'product_info',
                                                       'status',
                                                       'new_old_user_status',
                                                       'create_time',
                                                       'update_time',
                                                       'submit_type'])

        else:
            user_history_order = pd.DataFrame(user_history_order)
            user_history_order['app_order_id'] = user_history_order.app_order_id.astype(str)
            user_history_order = user_history_order[(user_history_order.apply_time <= current_apply_time) &
                                                    (
                                                            user_history_order.app_order_id != current_order_id)]  # 不包含本单，但是包含本批次数据
        user_history_order['app_type'] = user_history_order.acq_channel.apply(
            lambda x: 'self_app' if x == current_acq_channel else 'other_app')

        user_history_order['product_type'] = user_history_order.product_code.apply(
            lambda x: 'self_product' if x == current_product_code else 'other_product')
        user_history_order = get_order_format(user_history_df=user_history_order,
                                              current_apply_time=request_data.apply_time,
                                              register_time=register_time,
                                              country_id=self.country_id)
        user_history_order['app_order_id'] = user_history_order.app_order_id.astype(str)
        user_history_order['user_id'] = user_history_order.user_id.astype(str)

        # installment data
        user_history_installment = request_data.data_sources['installments_data_a']
        if not user_history_installment or user_history_installment == []:
            user_history_installment = pd.DataFrame(columns=['user_id',
                                                             'acq_channel',
                                                             'app_order_id',
                                                             'contract_no',
                                                             'repayment_date',
                                                             'installment_num',
                                                             'installment_amount',
                                                             'principal',
                                                             'interest',
                                                             'cut_interest',
                                                             'service_fee',
                                                             'management_fee',
                                                             'overdue_interest',
                                                             'overdue_days',
                                                             'penalty',
                                                             'extension_fee',
                                                             'repaid_principal',
                                                             'repaid_interest',
                                                             'repaid_cut_interest',
                                                             'repaid_service_fee',
                                                             'repaid_management_fee',
                                                             'repaid_overdue_interest',
                                                             'repaid_penalty',
                                                             'discount_amount',
                                                             'waive_amount',
                                                             'settlement_type',
                                                             'extension_count',
                                                             'status',
                                                             'create_time',
                                                             'update_time',
                                                             'repaid_principal',
                                                             'repaid_interest',
                                                             'repaid_cut_interest',
                                                             'repaid_service_fee',
                                                             'repaid_management_fee',
                                                             'repaid_overdue_interest',
                                                             'repaid_penalty',
                                                             'discount_amount',
                                                             'waive_amount',
                                                             'ovd_days',
                                                             'bill_category', 'repaid_amt_sum'
                                                             ])
        else:
            user_history_installment = pd.DataFrame(user_history_installment)
            user_history_installment = user_history_installment[
                user_history_installment.create_time < current_apply_time]
            user_history_installment[['repaid_principal',
                                      'repaid_interest',
                                      'repaid_cut_interest',
                                      'repaid_service_fee',
                                      'repaid_management_fee',
                                      'repaid_overdue_interest',
                                      'repaid_penalty',
                                      'discount_amount',
                                      'waive_amount',
                                      'ovd_days',
                                      'bill_category', 'repaid_amt_sum']] = user_history_installment.apply(
                get_bill_data,
                axis=1,
                result_type='expand',
                args=(current_apply_time,))
            user_history_installment['app_order_id'] = user_history_installment.app_order_id.astype(str)
            user_history_installment['user_id'] = user_history_installment.user_id.astype(str)

        # contract data
        user_history_contract = request_data.data_sources['contract_data_a']
        rst_data = {'current_info': current_info,
                    'user_history_order': user_history_order,
                    'user_history_installment': user_history_installment,
                    'user_history_contract': pd.DataFrame(user_history_contract)}
        self.data = rst_data

    def loan_order_features_v3(self):
        return LoanUnOrderV3.get_features(country_id=self.country_id, rst_data=self.data)

    def loan_payoff_features_v3(self):
        return LoanUnPayoffV3.get_features(rst_data=self.data)

    def loan_pre_payoff_features_v3(self):
        return LoanUnPrePayoffV3.get_features(rst_data=self.data)

    def loan_ovd_payoff_features_v3(self):
        return LoanUnOvdPayoffV3.get_features(rst_data=self.data)
